import datetime
import json
import math

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from .models import House, Area, Facility, HouseImage
from apps.order.models import Order
import logging
logger = logging.getLogger('django')
from ihome.utils.views import LoginRequiredJSONMixin
from django.db.models import Q

# Create your views here.

class HouseDetailsView(View):
    def get(self, request, house_id):

        try:
            # images = HouseImage.objects.filter(house_id=house_id)

            img_urls = []
            for img in range(0,5):
                img_urls.append('http://www.ihome.site:8080/img/8/1.jpg')
        except Exception as e:
            return JsonResponse({'errno': 4001, 'errmsg': '数据库查询错误'})

        try:
            order_models = Order.objects.filter(status=4, house_id=house_id)
            comments = []
            for order_model in order_models:
                comments.append({
                    "comment": order_model.comment,
                    "ctime": order_model.end_date,
                    "user_name": order_model.user.username
                })
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4001, 'errmsg': '数据库查询错误'})

        try:
            house = House.objects.get(id=house_id)

            facilities = house.facility.all()
            facilities_list = []
            for fac in facilities:
                facilities_list.append(fac.id)

            house_dict = {
                "acreage": house.acreage,
                "address": house.address,
                "beds": house.beds,
                "capacity": house.capacity,
                "comments": comments,
                "deposit": house.deposit,
                "facilities": facilities_list,
                "hid": house.id,
                "img_urls": img_urls,
                "max_days": house.max_days,
                "min_days": house.min_days,
                "price": house.price * 100,
                "room_count": house.room_count,
                "title": house.title,
                "unit": house.unit,
                "user_avatar": 'http://www.ihome.site:8080/img/%d.jpg' % house.user_id,
                "user_id": house.user_id,
                "user_name": house.user.username
            }
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4001, 'errmsg': '数据库查询错误'})

        return JsonResponse({
            "data":{
                "house": house_dict,
                "user_id":request.user.id
            },
            "errmsg":"OK",
            "errno":"0"
        })


class OwnHouseView(LoginRequiredJSONMixin, View):

    def get(self, request):

        user = request.user
        try:
            houses = House.objects.filter(user=user.id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4001, 'errmsg': '数据库查询错误'})

        houses_data = []

        for house in houses:
            houses_data.append({
                "address": house.address,
                "area_name": house.area.name,
                "ctime": house.update_time,
                "house_id": house.id,
                "img_url": 'http://www.ihome.site:8080/img/8/1.jpg',
                "order_count": house.order_count,
                "price": house.price * 100,
                "room_count": house.room_count,
                "title": house.title,
                "user_avatar": 'http://www.ihome.site:8080/img/%d.jpeg' % house.user_id
            })

        return JsonResponse({
            "data": {
                "houses": houses_data
            },
            "errmsg": "ok",
            "errno": "0"
        })


class CreateHouseView(View):

    def post(self, request):
        json_dict = json.loads(request.body.decode())

        title = json_dict.get('title')
        price = json_dict.get('price')
        area_id = json_dict.get('area_id')
        address = json_dict.get('address')
        room_count = json_dict.get('room_count')
        acreage = json_dict.get('acreage')
        unit = json_dict.get('unit')
        capacity = json_dict.get('capacity')
        beds = json_dict.get('beds')
        deposit = json_dict.get('deposit')
        min_days = json_dict.get('min_days')
        max_days = json_dict.get('max_days')
        facility = json_dict.get('facility')

        if not all([title, price, area_id, address, room_count, acreage, unit, capacity, beds, deposit, min_days,
                    max_days, facility]):
            return JsonResponse({'errno': 4002, 'errmsg': '缺少必传参数'})

        try:
            area_id = int(area_id)
            room_count = int(room_count)
            acreage = int(acreage)
            capacity = int(capacity)
            min_days = int(min_days)
            max_days = int(max_days)
        except Exception as e:
            return JsonResponse({'errno': 4103, 'errmsg': '数据格式有误'})

        try:
            area = Area.objects.get(id=area_id)
            for fac in facility:
                Facility.objects.get(id=fac)
        except Exception as e:
            return JsonResponse({'errno': 4103, 'errmsg': '数据有误'})


        try:
            new_house = House(
                user=request.user,
                title=title,
                price=price,
                area_id=area_id,
                address=address,
                room_count=room_count,
                acreage=acreage,
                unit=unit,
                capacity=capacity,
                beds=beds,
                deposit=deposit,
                min_days=min_days,
                max_days=max_days
            )
            new_house.save()
            new_house.facility.add(*facility)

        except Exception as e:
            return JsonResponse({'errno': 4001, 'errmsg': '数据库保存错误'})

        return JsonResponse({
            "errno": "0",
            "errmsg": "发布成功",
            "data": {
                "house_id": new_house.id
            }
        })


    def get(self, request):
        area_id = request.GET.get('aid')   # 城区
        start = request.GET.get('sd')       # 开始日期
        end = request.GET.get('ed')         # 结束日期
        sk = request.GET.get('sk')          # 排序方案
        p = request.GET.get('p', 1)         # 页数

        if sk not in ['new', 'booking', 'price_inc', 'price_des']:
            return JsonResponse({'errno': 4103, 'errmsg': 'sk格式有误'})

        try:
            p = int(p)
        except Exception as e:
            return JsonResponse({'errno': 4103, 'errmsg': 'p格式有误'})


        houses = House.objects.all()

        if all([start, end]):
            try:
                start_day = datetime.datetime.strptime(start, '%Y-%m-%d')
                end_day = datetime.datetime.strptime(end, '%Y-%m-%d')
                live_days = (end_day - start_day).days
                houses = houses.filter(Q(min_days__lte=live_days, max_days__gte=live_days) | Q(max_days=0))
            except Exception as e:
                return JsonResponse({'errno': 4103, 'errmsg': 'sd格式有误'})

        if area_id:
            try:
                houses = houses.filter(area_id=area_id)
            except Exception as e:
                logger.error(e)
                return JsonResponse({'errno': 4001, 'errmsg': '数据库读写错误'})


        if sk == 'new':  # 最新上线
            houses.order_by('-update_time')
        elif sk == 'booking': # 入住最多
            houses.order_by('-order_count')
        elif sk == 'price_inc': # 价格由低到高
            houses.order_by('price')
        else: # 价格由高到低
            houses.order_by('-price')

        try:
            house_list = []
            houses_count = houses.count()
            start_index = 5 * (p - 1)
            if houses_count < 5 * p:
                end_index = houses_count
            else:
                end_index = 5 * p
            for house in houses[start_index: end_index]:
                house_list.append({
                    "address": house.address,
                    "area_name": house.area.name,
                    "ctime": house.update_time,
                    "house_id": house.id,
                    "img_url": 'http://www.ihome.site:8080/img/8/1.jpg',
                    "order_count": house.order_count,
                    # TODO: 检查前端单位
                    "price": house.price * 100,
                    "room_count": house.room_count,
                    "title": house.title,
                    "user_avatar": 'http://www.ihome.site:8080/img/2.jpg'
                })
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4001, 'errmsg': '数据库读写错误'})

        return JsonResponse({
            "data":{
                "houses": house_list,
                "total_page": math.ceil(houses_count / 5)
            },
            "errmsg":"请求成功",
            "errno":"0"
        })


class HouseRecommendationView(View):

    def get(self, request):
        """首页房屋推荐"""
        try:
            houses = House.objects.all()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4001, 'errmsg': '数据库查询错误'})

        data =[]

        index = 0
        for house in houses:
            data.append({
                'house_id': house.id,
                'img_url': 'http://www.ihome.site:8080/img/8/1.jpg',
                'title': house.title
            })
            if len(data) >= 5:
                break

        return JsonResponse({"data": data,
                             "errmsg": "OK",
                             "errno": "0"})


class AreaView(View):

    def get(self, request):

        try:
            areas = Area.objects.all()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4001, 'errmsg': '数据库查询错误'})

        data = []

        for area in areas:
            data.append({
                'aid': area.id,
                'aname': area.name
            })

        return JsonResponse({
            "errmsg": "获取成功",
            "errno": "0",
            "data": data
        })





